<?php
RegisterPlugin('Zblog_Eloquent_ORM', 'ActivePlugin_Zblog_Eloquent_ORM');

function ActivePlugin_Zblog_Eloquent_ORM() {
	Add_Filter_Plugin('Filter_Plugin_Zbp_PreLoad', 'Filter_Plugin_Zbp_PreLoad_Zblog_Eloquent_ORM');
	Add_Filter_Plugin('Filter_Plugin_Zbp_Set', 'Filter_Plugin_Zbp_Set_Zblog_Eloquent_ORM');
}

function Zblog_Eloquent_ORM_SubMenu($id) {
	global $zbp;
	$arySubMenu = array(
		array('插件说明', 'explain', 'left', false),
		array('数据库管理', 'database', 'left', false),
		array('数据库配置', 'mysql', 'left', false),
	);
	foreach ($arySubMenu as $v) {
		echo '<a href="?act=' . $v[1] . '"><span class="m-' . $v[2] . ' ' . ($id == $v[1] ? 'm-now' : '') . '">' . $v[0] . '</span></a>';
	}
}

function Zblog_Eloquent_ORM_Format_Bytes($size, $delimiter = '') {
	global $zbp;
	$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
	for ($i = 0; $size >= 1024 && $i < 5; $i++) {
		$size /= 1024;
	}

	return round($size, 2) . ' ' . $delimiter . $units[$i];
}

function Zblog_Eloquent_ORM_Get_Databases() {
	global $zbp;
	$sql = "SHOW TABLE STATUS";
	return $zbp->db->Query($sql);
}

function Zblog_Eloquent_ORM_Myisam_To_Innodb() {
	global $zbp;
	$database = Zblog_Eloquent_ORM_Get_Databases();
	foreach ($database as $item) {
		if ($item['Engine'] == 'MyISAM') {
			$sql = "alter table `{$item['Name']}` engine = innodb";
			$zbp->db->Query($sql);
		}
	}
	return true;
}

function Zblog_Eloquent_ORM_Innodb_To_Myisam() {
	global $zbp;
	$database = Zblog_Eloquent_ORM_Get_Databases();
	foreach ($database as $item) {
		if ($item['Engine'] == 'InnoDB') {
			$sql = "alter table `{$item['Name']}` engine = myisam";
			$zbp->db->Query($sql);
		}
	}
	return true;
}

function Zblog_Eloquent_ORM_Collation_To_Utf8Mb4() {
    global $zbp;
    $database = Zblog_Eloquent_ORM_Get_Databases();
    foreach ($database as $item) {
        if ($item['Collation'] !== 'utf8mb4_general_ci') {
            $sql = "alter table `{$item['Name']}` convert to character set 'utf8mb4' COLLATE 'utf8mb4_general_ci'";
            $zbp->db->Query($sql);
        }
    }
    return true;
}

function Zblog_Eloquent_ORM_ChangeEngine($name, $engine) {
    global $zbp;
    $database = Zblog_Eloquent_ORM_Get_Databases();
    foreach ($database as $item) {
        if ($item['Name'] == $name) {
            $sql = "alter table `{$item['Name']}` engine = $engine";
            $zbp->db->Query($sql);
        }
    }
    return true;
}

function Zblog_Eloquent_ORM_Get_Connection($name = '')
{
    global $zbp;
    /** @var \Illuminate\Database\Connection */
    return $zbp->Zblog_Eloquent_ORM->getConnection($name);
}

function Filter_Plugin_Zbp_Set_Zblog_Eloquent_ORM($name, $value)
{
    global $zbp;
    if ($name === 'Zblog_Eloquent_ORM') {
        $GLOBALS['Filter_Plugin_Zbp_Set']['Filter_Plugin_Zbp_Set_Zblog_Eloquent_ORM'] = PLUGIN_EXITSIGNAL_RETURN;
        $zbp->Zblog_Eloquent_ORM = $value;
    }
}

function Filter_Plugin_Zbp_PreLoad_Zblog_Eloquent_ORM() {
	global $zbp;
	include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . '/vendor/autoload.php';
	$manager = new \Illuminate\Database\Capsule\Manager;
	$manager->addConnection(Zblog_Eloquent_ORM_Config());
    $mysql = $zbp->Config('Zblog_Eloquent_ORM')->mysql;
    if (!empty($mysql)) {
        foreach ($mysql as $item) {
            $manager->addConnection($item, $item['ident']);
        }
    }
	$manager->setEventDispatcher(new \Illuminate\Events\Dispatcher(new \Illuminate\Container\Container));
	$manager->setAsGlobal();
	$manager->bootEloquent();
    $zbp->Zblog_Eloquent_ORM = $manager;

	\Illuminate\Pagination\Paginator::currentPathResolver(function () use ($zbp) {
		return \Base\Pagination::handleUrlQuery($zbp->fullcurrenturl);
	});
}

function Zblog_Eloquent_ORM_Config() {
	switch ($GLOBALS['option']['ZC_DATABASE_TYPE']) {
	case 'sqlite':
	case 'sqlite3':
	case 'pdo_sqlite':
		$config = [
			'driver' => 'sqlite',
			'host' => $GLOBALS['option']['ZC_MYSQL_SERVER'],
			'database' => $GLOBALS['option']['ZC_SQLITE_NAME'],
			'username' => $GLOBALS['option']['ZC_MYSQL_USERNAME'],
			'password' => $GLOBALS['option']['ZC_MYSQL_PASSWORD'],
			'charset' => $GLOBALS['option']['ZC_MYSQL_CHARSET'],
			'port' => $GLOBALS['option']['ZC_MYSQL_PORT'],
			'collation' => $GLOBALS['option']['ZC_MYSQL_COLLATE'],
			'prefix' => $GLOBALS['option']['ZC_SQLITE_PRE'],
		];
		break;
	case 'postgresql':
	case 'pdo_postgresql':
		$config = [
			'driver' => 'pgsql',
			'host' => $GLOBALS['option']['ZC_PGSQL_SERVER'],
			'database' => $GLOBALS['option']['ZC_PGSQL_NAME'],
			'username' => $GLOBALS['option']['ZC_PGSQL_USERNAME'],
			'password' => $GLOBALS['option']['ZC_PGSQL_PASSWORD'],
			'charset' => $GLOBALS['option']['ZC_PGSQL_CHARSET'],
			'port' => $GLOBALS['option']['ZC_PGSQL_PORT'],
			'collation' => $GLOBALS['option']['ZC_MYSQL_COLLATE'],
			'prefix' => $GLOBALS['option']['ZC_PGSQL_PRE'],
		];
		break;
	case 'mysql':
	case 'mysqli':
	case 'pdo_mysql':
	default:
		$config = [
			'driver' => 'mysql',
			'host' => $GLOBALS['option']['ZC_MYSQL_SERVER'],
			'database' => $GLOBALS['option']['ZC_MYSQL_NAME'],
			'username' => $GLOBALS['option']['ZC_MYSQL_USERNAME'],
			'password' => $GLOBALS['option']['ZC_MYSQL_PASSWORD'],
			'charset' => $GLOBALS['option']['ZC_MYSQL_CHARSET'],
			'port' => $GLOBALS['option']['ZC_MYSQL_PORT'],
			'collation' => $GLOBALS['option']['ZC_MYSQL_COLLATE'],
			'prefix' => $GLOBALS['option']['ZC_MYSQL_PRE'],
		];
		break;
	}

	return $config;
}

function InstallPlugin_Zblog_Eloquent_ORM() {}

function UninstallPlugin_Zblog_Eloquent_ORM() {}
